﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q.Spider.Core.Models
{
    /// <summary>
    /// 请求
    /// </summary>
    public class Request
    {
        public Uri Uri { get; set; }

        public Request(string url, string name = "未命名")
        {
            Uri = new Uri(url);
            Name = name;
        }


        public List<Type>? FlowTpyes { get; set; }


        /// <summary>
        /// 深度
        /// </summary>
        public int Depth { get; set; } = 0;

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        public int ErrorCount { get; set; } = 0;

        /// <summary>
        /// 自定义属性
        /// </summary>
        public Dictionary<string, string> Properties { get; set; } = new();


        public T? GetProperties<T>(string key)
        {
            if (!Properties.ContainsKey(key))
            {
                return default;
            }
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(Properties[key]);
        }
        public void AddProperties(string key, object value)
        {
            var josnStr = Newtonsoft.Json.JsonConvert.SerializeObject(value);
            //JSON反序列化
            //var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(josnStr);

            Properties.Add(key, josnStr);
        }

        /// <summary>
        /// 克隆一个请求，请求层级+1
        /// </summary>
        /// <param name="newUrl">新的请求地址</param>
        /// <returns></returns>
        public Request Clone(string newUrl)
        {
            //如果是通过克隆掉的  就肯定是详情页 所以 层级+1
            var request = new Request(newUrl)
            {
                Depth = Depth + 1,
                ErrorCount = ErrorCount,
                Name = Name
            };
            foreach (var item in Properties)
            {
                request.Properties.Add(item.Key, item.Value);
            }
            return request;
        }

    }
}
